import { Request, Response, NextFunction } from 'express';
import Jimp from 'jimp';
import multer from 'multer';
import { imageResizer } from './house.service';

/**
 * 创建一个 multer
 */
const fileUpload = multer({
  dest: 'uploads/houses/'
})

/**
 * 文件拦截器
 */
export const fileInterceptor = fileUpload.single('file')

/**
 * 文件处理器
 */
export const fileProcessor = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 文件路径
  const { path } = request.file;

  let image: Jimp;

  try {
    // 读取图像文件
    image = await Jimp.read(path);
  } catch (error) {
    return next(error);
  }
  
  if (image['_exif'] !== null ) {
    // 准备文件数据
    let { imageSize, tags } = image['_exif'];
    // 在请求中添加文件数据
    request.fileMataData = {
      width: imageSize.width,
      height: imageSize.height,
      metadata: JSON.stringify(tags)
    }
  } else {
    // 在请求中添加文件数据
    request.fileMataData = {
      width: 0,
      height: 0,
      metadata: null
    }
  }

  // 调整图像尺寸
  imageResizer(image, request.file);

  // 下一步
  next();
}
